package cn.terys.terystransactionclient;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import cn.emagsoftware.ui.ToastManager;
import cn.emagsoftware.ui.adapterview.DataHolder;
import cn.emagsoftware.ui.adapterview.GenericAdapter;
import cn.emagsoftware.ui.adapterview.ViewHolder;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.LogManager;
import cn.terys.terystransactionclient.data.SPManager;
import cn.terys.terystransactionclient.data.User;
import cn.terys.terystransactionclient.data.UserManager;

public class OperatorManageActivity extends BaseActivity
{

    GenericAdapter listAdapter = new GenericAdapter(this);
    String         id          = "";
    String         content     = "";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        if (!WelcomeActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, WelcomeActivity.class);
            return;
        }
        setContentView(R.layout.operatormanage);
        setTitle(R.string.operatormanage_title);
        final EditText userid = (EditText) findViewById(R.id.userid);
        final EditText contentEdit = (EditText) findViewById(R.id.content);
        Button query = (Button) findViewById(R.id.query);
        query.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                query(userid.getText().toString(), contentEdit.getText().toString());
            }
        });
        Button add = (Button) findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                Intent intent = new Intent(OperatorManageActivity.this, UserInputActivity.class);
                startActivity(intent);
            }
        });
        Button cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
        });
        ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(listAdapter);
        query(userid.getText().toString(), contentEdit.getText().toString());
    }

    @Override
    protected void onRestart()
    {
        // TODO Auto-generated method stub
        super.onRestart();
        query(id, content);
    }

    private void query(String id, String content)
    {
        this.id = id;
        this.content = content;
        List<User> users = null;
        try
        {
            users = UserManager.getOperatorUsers(id, content);
        } catch (Exception e)
        {
            LogManager.logE(OperatorManageActivity.class, "query failed.", e);
            ToastManager.showLong(this, R.string.operatormanage_query_failed);
            return;
        }
        listAdapter.clearDataHolders();
        int size = users.size();
        if (size == 0)
        {
            ToastManager.showLong(this, R.string.operatormanage_query_empty);
            return;
        }
        List<DataHolder> holders = new ArrayList<DataHolder>(size);
        Iterator<User> userIterator = users.iterator();
        final String idDesc = getString(R.string.operatormanage_list_item_userid);
        final String nameDesc = getString(R.string.operatormanage_list_item_name);
        final String contentDesc = getString(R.string.operatormanage_list_item_content);
        while (userIterator.hasNext())
        {
            holders.add(new DataHolder(userIterator.next(), 0)
            {
                @Override
                public View onCreateView(Context arg0, int arg1, Object arg2)
                {
                    // TODO Auto-generated method stub
                    View item = getLayoutInflater().inflate(R.layout.operatormanage_list_item, null);
                    TextView id = (TextView) item.findViewById(R.id.userid);
                    TextView name = (TextView) item.findViewById(R.id.name);
                    TextView content = (TextView) item.findViewById(R.id.content);
                    Button edit = (Button) item.findViewById(R.id.edit);
                    Button delete = (Button) item.findViewById(R.id.delete);
                    item.setTag(new ViewHolder(id, name, content, edit, delete));
                    onUpdateView(arg0, arg1, item, arg2);
                    return item;
                }

                @Override
                public void onUpdateView(Context arg0, final int arg1, View arg2, Object arg3)
                {
                    // TODO Auto-generated method stub
                    final User user = (User) arg3;
                    View[] views = ((ViewHolder) arg2.getTag()).getParams();
                    ((TextView) views[0]).setText(idDesc + user.id);
                    ((TextView) views[1]).setText(nameDesc + user.name);
                    ((TextView) views[2]).setText(contentDesc + user.content);
                    views[3].setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent(OperatorManageActivity.this, UserInputActivity.class);
                            intent.putExtra(ManageActivity.INTENT_EXTRANAME_USER, user);
                            intent.putExtra(ManageActivity.INTENT_EXTRANAME_VERIFYOLDPWD, false);
                            startActivity(intent);
                        }
                    });
                    views[4].setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            // TODO Auto-generated method stub
                            DialogManager.showAlertDialog(OperatorManageActivity.this, R.string.generic_dialog_title, R.string.operatormanage_list_item_delete_tip, new int[] {
                                    R.string.generic_dialog_btn_ok, R.string.generic_dialog_btn_cancel }, new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    // TODO Auto-generated method stub
                                    if (which == DialogInterface.BUTTON_POSITIVE)
                                    {
                                        String[] signedUser = SPManager.getUserSignedTag(OperatorManageActivity.this);
                                        if (user.id.equalsIgnoreCase(signedUser[0]))
                                        {
                                            ToastManager.showLong(OperatorManageActivity.this, R.string.operatormanage_list_item_delete_conflict);
                                            return;
                                        }
                                        String result = UserManager.deleteUser(OperatorManageActivity.this, user);
                                        if (result == null)
                                        {
                                            ToastManager.showLong(OperatorManageActivity.this, R.string.operatormanage_list_item_delete_success);
                                            listAdapter.removeDataHolder(arg1);
                                        } else
                                        {
                                            ToastManager.showLong(OperatorManageActivity.this, result);
                                        }
                                    }
                                }
                            }, true, false);
                        }
                    });
                }

                @Override
                public void onAsyncDataExecuted(Context arg0, int arg1, View arg2, Object arg3, int arg4)
                {
                    // TODO Auto-generated method stub
                }
            });
        }
        listAdapter.addDataHolders(holders);
    }

}